﻿using MediatR;
using NPOI.Util;
using T.Basic.Domain.T.Basic.Dto;
using T.Basic.Domain.T.Basic.Model;
using T.Basic.Read.API.Appliction.Command.VehicleCommand;
using T.Basic.Repository.BasicInterface;

namespace T.Basic.Read.API.Appliction.CommandHandlers.VehicleHanders
{
    /// <summary>
    /// 显示车辆信息
    /// </summary>
    public class VehicleListCommandHandler : IRequestHandler<VehicleListCommand, PageDto<Vehicle>>
    {
        private readonly IVehicleRepository _vehicleRepository;
        public VehicleListCommandHandler(IVehicleRepository vehicleRepository)
        {
            _vehicleRepository = vehicleRepository;
        }

        public async Task<PageDto<Vehicle>> Handle(VehicleListCommand request, CancellationToken cancellationToken)
        {
            PageDto<Vehicle> pageDto = new PageDto<Vehicle>();
            var ShowVehicle = await _vehicleRepository.GetAsync(d => !d.IsDeleted);
            if (!string.IsNullOrEmpty(request.CompanyID))
            {
                ShowVehicle = ShowVehicle.Where(d => d.CompanyID == request.CompanyID).ToList();
            }
            if (!string.IsNullOrEmpty(request.BrandAndModel))
            {
                ShowVehicle= ShowVehicle.Where(d=>d.BrandAndModel.Contains(request.BrandAndModel)).ToList();
            }
            if (!string.IsNullOrEmpty(request.PlateNumber))
            {
                ShowVehicle = ShowVehicle.Where(d => d.PlateNumber.Contains(request.PlateNumber)).ToList();
            }
            if (!string.IsNullOrEmpty(request.DriverName))
            {
                ShowVehicle = ShowVehicle.Where(d => d.DriverName.Contains(request.DriverName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.BelongingCompany))
            {
                ShowVehicle = ShowVehicle.Where(d => d.BelongingCompany.Contains(request.BelongingCompany)).ToList();
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize == null)
            {
                request.PageSize = ShowVehicle.Count();
            }
            var size = request.PageSize;
            var index = request.PageIndex;
            pageDto.TotalCount = ShowVehicle.Count();
            pageDto.PageCount = (int)Math.Ceiling(pageDto.PageCount * 1.0 / (int)size);
            pageDto.list = ShowVehicle.OrderByDescending(d => d.CreatedDate).Skip(((int)index - 1) * (int)size).Take((int)size).ToList();
            return pageDto;
            //pageDtos.TotalCount = ShowVehicle.Count();
            //pageDtos.PageCount = (int)Math.Ceiling(pageDtos.TotalCount * 1.0 / request.PageSize);
            //pageDtos.list = ShowVehicle.OrderByDescending(d => d.CreatedDate).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            //return pageDtos;
        }
    }
}
